<!-- 预约 -->
<template>
	<view class="container">
		<!-- banner -->
		<view class="banner"></view>
		
		<!-- form -->
		<!-- form title -->
		<view class="form-title">
			<view>预约绑卡</view>
			<!-- <view>
				<uni-icons type="info"></uni-icons>
				<view @click="toUrl(`/pagesActivity/ACTE017/appointmentRecods?params=${JSON.stringify(vdata.params)}`)">预约记录</view>
			</view> -->
		</view>
		<form @submit="formSubmit">
			<view class="form">
				<view class="uni-form-item uni-column">
					<view class="title">姓名</view>
					<view class="input">
						<input type="text" name="name" placeholder="请输入姓名" :value="vdata.echo.name">
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="title">电话</view>
					<view class="input">
						<input type="tel" maxlength="11" name="telphone" placeholder="请输入电话" :value="vdata.echo.telphone">
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="title">选择预约网点</view>
					<view class="input">
						<picker mode="multiSelector" :range="[vdata.countyList,vdata.dotList]" :value="vdata.index" range-key="agentName" @change="onPickerChange" @cancel="onPickerCancel" @columnchange="onPickerColumnChange">
							<view v-if="vdata.agentNoIndex?.length >= 2">{{ vdata.agentList[vdata.agentNoIndex[0]].agentName + '/' + vdata.agentList[vdata.agentNoIndex[0]].children[vdata.agentNoIndex[1]].agentName }}</view>
							<view v-else style="color: #808080;">请选择</view>
						</picker>
					</view>
					<uni-icons type="right" size="24" color="#acacac"></uni-icons>
				</view>
				<view class="uni-form-item uni-column">
					<view class="title">选择预约时间</view>
					<view class="input">
						<picker mode="date" :value="vdata.date" @change="dateBindPickerChange" :start="dayjs().format('YYYY-MM-DD')" :end="dayjs(vdata.params.eTime).format('YYYY-MM-DD')">
							<view v-if="vdata.date">{{ vdata.date }}</view>
							<view v-else style="color: #808080;">请选择</view>
						</picker>
					</view>
					<uni-icons type="calendar" size="24" color="#acacac"></uni-icons>
				</view>
			</view>
			<view class="btn-wrap">
				<button form-type="submit" class="submit" plain>{{ vdata.fansAwardId === null ? '点击预约' : '修改预约' }}</button>
				<button v-if="vdata.fansAwardId && vdata.awardId" class="submit" plain @click="onActivate">{{ vdata.state === 0 ? '去使用' : vdata.state === 1 ? '已使用' : vdata.state === 2 ? '已过期' : vdata.state === 3 ? '去领取' : '已失效' }}</button>
			</view>
			<view class="tips">
				<view class="title">温馨提示</view>
				<view>请携带本人身份证及业务相关的银行卡核销礼品</view>
			</view>
		</form>
	</view>
</template>

<script setup>
	import { ref, reactive, getCurrentInstance } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { $getNearAgentNo, $appointSendAward, $getAppointSendAward } from '@/http/apiManager.js'
	import storageManage from '@/util/storageManage.js'
	import dayjs from 'dayjs'
	import appConfig from '@/config/appConfig.js'
	import getLocation from '@/util/location.js'	// 授权 拉取定位信息 异步函数 返回 经纬度和地址信息
	
	// #ifdef MP-YHDD
	import agents from '@/components/applyJson/agentsCc.json'
	// #endif
	// #ifndef MP-YHDD
	import agents from '@/components/applyJson/agentsZz.json'
	// #endif
	
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
	
	// 数据源
	const vdata = reactive({
		agentNo: '',	// 预约网点
		date: '',	// 预约时间
		params: {},	// 发放奖品参数
		
		// 网点
		agentNoIndex: [],
		index: [],	// 选中的网点下标 (内部滚动重置 列表使用)
		agentList: agents.list,	// 网点列表
		countyList: agents.list,	// 区县列表
		dotList: agents.list[0].children,	// 网点列表
		
		// 姓名 手机号 预约网点回显
		echo: {
			name: storageManage.userInfo().realName,
			telphone: storageManage.userInfo().phone,
		},
		
		fansAwardId: null,	// 新增OR修改预约信息
		awardId: null,	// 跳转奖品详情页面
		state: 0,	// 奖品状态
	})
	
	onLoad(({ params }) => {
		vdata.params = JSON.parse(params)
		// 获取预约信息
		getAppointSendAward(vdata.params)
	})
	
	/**
	 * 选择归属网点
	 */
	function onPickerChange({ detail }){
		const { value } = detail
		if(JSON.stringify(value) !== JSON.stringify(vdata.agentNoIndex)){
			vdata.agentNoIndex = value
		}
	}
	/**
	 * 取消归属网点选择 列表位置 重置为当前选中的网点
	 */
	function onPickerCancel(e){
		vdata.index = JSON.parse(JSON.stringify(vdata.agentNoIndex))
	}
	/**
	 * 切换第二列
	 */
	function onPickerColumnChange({ detail }){
		const { column, value } = detail
		if(column === 0){
			vdata.dotList = agents.list[value].children
			vdata.index = [value,0]
		}
	}
	/**
	 * 预约网点 选择
	 */
	const agentBindPickerChange = (e) => {
		vdata.agentIndex = e.detail.value
	}
	/**
	 * 预约时间 选择
	 */
	const dateBindPickerChange = (e) => {
		vdata.date = e.detail.value
	}
	/**
	 * 表单提交
	 */
	const formSubmit = (e) => {
		const formdata = e.detail.value
		const saveObject = {
			agentNo: vdata.agentList[vdata.agentNoIndex[0]].children[vdata.agentNoIndex[1]].agentNo,
			gswdPid: vdata.agentList[vdata.agentNoIndex[0]].agentNo,
			appointTime: vdata.date,
		}
		if(vdata.fansAwardId){	// 修改预约信息
			saveObject.fansAwardId = vdata.fansAwardId
		}
		Object.assign(formdata,saveObject)
		// 校验手机号信息
		if(!/^(?:(?:\+|00)86)?1\d{10}$/.test(formdata.telphone)){
			$infoBox.toast('请输入正确的手机号')
			return
		}
		// 信息校验
		for(let key in formdata){
			if(!formdata[key]){
				$infoBox.toast('请完善预约信息')
				return
			}
		}
		getApp().preventActive(() => {
			// 提交预约信息 发放一张未激活 D券
			uni.showLoading({ title: '加载中' })
			$appointSendAward({ ...vdata.params, ...formdata }).then(({ bizData }) => {
				uni.hideLoading()
				if(vdata.fansAwardId){
					$infoBox.toast('修改成功')
				}else{
					$infoBox.toast('预约成功')
				}
				vdata.awardId = bizData.awardId
				vdata.fansAwardId = bizData.fansAwardId
				vdata.state = bizData.state
			})
		})
	}
	/**
	 * 去激活
	 */
	const onActivate = () => {
		uni.navigateTo({
			url: '/pageUser/myAward/viewInfo?fansAwardId=' + vdata.fansAwardId + '&goodsId=' + vdata.awardId
		})
	}
	/**
	 * 获取预约信息
	 */
	const getAppointSendAward = (data) => {
		$getAppointSendAward(data).then(async ({ bizData }) => {
			if(bizData){	// 存在预约信息 回显预约信息
				Object.assign(bizData,JSON.parse(bizData.extraJson))
				const { fansAwardId, awardId, state, name, telphone, appointTime, project, gswdPid, agentNo } = bizData
				vdata.fansAwardId = fansAwardId
				vdata.awardId = awardId
				vdata.state = state
				vdata.echo.name = name
				vdata.echo.telphone = telphone
				vdata.date = appointTime
				agentEchoHandle({ gswdPid, gswdAgentNo: agentNo })
			}else{	// 否则回显 归属网点
				// 否则请求 位置授权 获取最近网点信息 如果授权失败 使用归属网点信息
				const { longitude, latitude, address, isReject } = await getLocation()
				if(isReject){	// 如果定位失败
					// 定位获取失败 无法获取最近网点信息 使用归属网点信息
					agentEchoHandle({ gswdPid: storageManage.userInfo().gswdPid, gswdAgentNo: storageManage.userInfo().gswdAgentNo })
				}else{	// 如果定位成功
					await getNearAgentNo(longitude,latitude)
				}
			}
		})
	}
	/**
	 * 请求最近的网点 并用于回显
	 */
	async function getNearAgentNo(lng,lat){
		const { bizData } = await $getNearAgentNo({ lng, lat })
		// 授权定位 使用 最近网点信息
		agentEchoHandle({ gswdPid: bizData.agent.pid, gswdAgentNo: bizData.agent.agentNo })
	}
	/**
	 * 预约网点 回显处理
	 */
	const agentEchoHandle = (agents) => {
		// 数据回显处理
		outer:
		for(let i in vdata.agentList){
			if(vdata.agentList[i].agentNo === agents.gswdPid){
				vdata.agentNoIndex[0] = i
				vdata.index[0] = i
				vdata.dotList = vdata.agentList[i].children
				for(let ii in vdata.agentList[i].children){
					if(vdata.agentList[i].children[ii].agentNo === agents.gswdAgentNo){
						vdata.agentNoIndex[1] = ii
						vdata.index[1] = ii
						break outer;	// 跳出最外层循环
					}
				}
			}
		}
	}
	/**
	 * 页面跳转
	 */
	const toUrl = (url) => {
		uni.navigateTo({
			url
		})
	}
</script>

<style lang="less" scoped>
	.container{
		width: 100%;
		min-height: 100vh;
		background-color: #f3f3f3;
		padding: 24rpx;
		box-sizing: border-box;
		
		.banner{
			width: 100%;
			// aspect-ratio: 9 / 4;
			background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/cd7387ad-b56b-4515-899a-fa79e4e2c9d9.png') no-repeat left top / 100% 100%;
			border-radius: 16rpx;
			height: 320rpx;
		}
		
		.form-title{
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin: 24rpx 0;
			
			view{
				&:nth-child(1){
					font-weight: bold;
					font-size: 36rpx;
				}
				&:nth-child(2){
					background-color: #e7e7e7;
					border-radius: 45rpx;
					padding: 5rpx 10rpx;
					color: #6f6f6f;
					font-size: 26rpx;
					display: flex;
					align-items: center;
				}
			}
		}
	
		.form{
			background-color: #fff;
			border-radius: 16rpx;
			
			.uni-form-item{
				border-bottom: 1rpx solid #f5f5f5;
				padding: 24rpx;
				display: flex;
				align-items: center;
				font-size: 28rpx;
				
				.title{
					min-width: 35%;
				}
				.input{
					flex-grow: 1;
				}
			}
		}
		
		.btn-wrap{
			display: flex;
			gap: 20rpx;
			.submit{
				flex: 1;
				margin-top: 24rpx;
				color: #fff;
				background-color: #75b424;
				border: none;
				border-radius: 45rpx;
				
				&:nth-child(2){
					background-color: #ffb00c;
				}
			}
		}
		
		.tips {
			margin-top: 28rpx;
			padding-bottom: 32rpx;
		
			view {
				margin-top: 15rpx;
				font-size: 26rpx;
				color: #666;
			}
		
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}
</style>